import asyncio
import time  
import websockets  
import json  
import requests 
import os  
import psutil
import win32process  
import win32con  
class RemoteDebugWebSocketClient:  
    def __init__(self, uri):  
        """  
        初始化 WebSocket 客户端  
  
        :param uri: WebSocket 服务器的 URI，例如 'ws://localhost:8765'  
        """  
        self.uri = uri  
        self.websocket = None  
    async def __aenter__(self):  
        await self.connect()  
        return self  
  
    async def __aexit__(self, exc_type, exc_val, exc_tb):  
        await self.close()  
    async def connect(self):  
        """  
        连接到 WebSocket 服务器  
        """  
        try:  
            self.websocket = await websockets.connect(self.uri)  
            print(f"Connected to {self.uri}")  
        except Exception as e:  
            print(f"Failed to connect to {self.uri}: {e}")  
  
    async def send_message(self, message):  
        """  
        发送消息到 WebSocket 服务器  
  
        :param message: 要发送的消息  
        """  
        if self.websocket:  
            try:  
                await self.websocket.send(message)  
                print(f"Sent: {message}")  
            except Exception as e:  
                print(f"Failed to send message: {e}")  
        else:  
            print("WebSocket is not connected.")  
  
    async def receive_message(self):  
        """  
        接收来自 WebSocket 服务器的消息  
        """  
        if self.websocket:  
            try:  
                message = await self.websocket.recv()  
                print(f"Received: {message}")  
                return message  
            except Exception as e:  
                print(f"Failed to receive message: {e}")  
        else:  
            print("WebSocket is not connected.")  
            return None  
  
    async def close(self):  
        """  
        关闭 WebSocket 连接  
        """  
        if self.websocket:  
            try:  
                await self.websocket.close()  
                print("WebSocket connection closed.")  
            except Exception as e:  
                print(f"Failed to close WebSocket: {e}")  

    async def execute_js(self, script):  
        """  
        在远程浏览器上下文中执行 JavaScript 脚本。  
  
        :param script: 要执行的 JavaScript 脚本。  
        :return: 脚本执行的结果。  
        """  
        if not self.websocket:  
            print("WebSocket is not connected.")  
            return None  
  
        command = {  
            "id": 1,  # 消息 ID，可以是任何整数，通常用于匹配响应  
            "method": "Runtime.evaluate",  
            "params": {  
                "expression": script,  # 要执行的 JavaScript 表达式  
                "context": "page",     # 执行上下文，通常是 "page"  
                "returnByValue": True  # 是否以值的形式返回结果  
            }  
        }  
  
        try:  
            await self.websocket.send(json.dumps(command))  
            response = await self.websocket.recv()  
            response_data = json.loads(response)  
              
            # 检查响应是否有错误  
            if "error" in response_data:  
                print(f"Error executing JavaScript: {response_data['error']}")  
                return None  
              
            # 提取结果  
            result = response_data.get("result", {}).get("result", {}).get("value")
            return result  
        except Exception as e:  
            print(f"Failed to execute JavaScript: {e}")  
            return None  
    #输入账号密码
    async def inputAccountAndPassword(self, username, password):  
        # 使用f-string格式化JavaScript代码，将username和password嵌入其中  
        js_code = f"""  
        function changeReactInputValue(inputDom,newText){{
            let lastValue = inputDom.value;
            inputDom.value = newText;
            let event = new Event('input', {{ bubbles: true }});
            event.simulated = true;
            let tracker = inputDom._valueTracker;
            if (tracker) {{
            tracker.setValue(lastValue);
            }}
            inputDom.dispatchEvent(event);
            }}
         var ret = false
        // 点击库（这里可能是指触发某些JavaScript事件或操作，但代码中并未实现）  
        var elements = document.getElementsByClassName("_2GBWeup5cttgbTw8FM3tfx");  
        // 遍历所有获取到的元素  
   
        for (var i = 0; i < elements.length; i++) {{  
            if (elements[i].type == "text") {{  
                changeReactInputValue(elements[i] , "{username}")

                ret = true
            }}  
            if (elements[i].type == "password") {{  
                changeReactInputValue(elements[i] , "{password}")
                ret = true
            }}  
        }}  

        """  

        ret = await self.execute_js(js_code)  
        # 执行JavaScript代码  
        return  ret
    
        #点击登录按钮
    async def clickLoginButton(self):
        # 使用f-string格式化JavaScript代码，将username和password嵌入其中  
        js_code = """  
 var buttons = document.getElementsByClassName("DjSvCZoKKfoNSmarsEcTS");  
  
// 遍历所有获取到的按钮  
for (var i = 0; i < buttons.length; i++) {  
    // 检查按钮的 type 属性是否为 "submit"  
    if (buttons[i].type === "submit") {  
        // 点击按钮  
        buttons[i].click();  
        // 如果只需要点击第一个匹配的按钮，可以在这里退出循环  
        break;  
    }  
}
      
        """    
        ret = await self.execute_js(js_code)  
        # 执行JavaScript代码  
        return  ret
    #开始游戏
    async def startGame(self):
        result = await self.execute_js("""  
        // 点击库  
        var elements = document.getElementsByClassName("_19axKcqYRuaJ8vdYKYmtTQ");  
        var ret = false;
        // 初始化一个计数器来跟踪点击的元素数量  
       
        // 遍历所有获取到的元素  
        for (var i = 0; i < elements.length; i++) {  
            // 触发每个元素的点击事件   
            if(elements[i].textContent == "库")
            {
                elements[i].click();
                break;
            }
        }  

        //点击 THRONE AND LIBERTY               
        elements = document.getElementsByClassName("_1vO6BoiVslZgs1kqDGdUs8 _2wgFGloLUdbOVEeIYkuqTp");
        for (var i = 0; i < elements.length; i++) {  
            // 触发每个元素的点击事件   
            elements[i].click();           
        }     

        //点击开始游戏
        elements = document.getElementsByClassName("_33cnXIqTRgRr49_FNXIHj6");
        for (var i = 0; i < elements.length; i++) {  
            // 触发每个元素的点击事件
            if(elements[i].textContent == "开始游戏")
            {
                elements[i].click();
                ret = true;
                break;
            }         
        } 
                                                                                     
    """)  
        return result
    #登录
    @staticmethod 
    async def login(username, password , steam_path):
        await RemoteDebugWebSocketClient.killSteam()
        time.sleep(1)
        directory_path = os.path.dirname(steam_path) 
        try:  
            os.remove(directory_path + "\\config\\loginusers.vdf")
        except Exception as e:  
            pass
        
        exit_code = os.system("E:\\steam\\steam.exe  -applaunch 2429640")  
        time.sleep(0.5)
        exit_code = os.system(f"E:\\project\\afapi\\startSteam.exe {steam_path}")  
        while True:
            #steam主界面逻辑
            jsonObj = await RemoteDebugWebSocketClient.getSteamPage("Steam")
            if jsonObj:
               async with RemoteDebugWebSocketClient(jsonObj["webSocketDebuggerUrl"]) as client:  
                is_successful = await client.startGame()  
                if is_successful:  
                    print("点击开始游戏")  
                    return True
                
            #steam登录主界面
            jsonObj = await RemoteDebugWebSocketClient.getSteamPage("登录 Steam")
            if jsonObj:
                async with RemoteDebugWebSocketClient(jsonObj["webSocketDebuggerUrl"]) as client:  
                    is_successful = await client.inputAccountAndPassword(username, password)
                    time.sleep(1)
                    await client.clickLoginButton()
                    if is_successful:
                        print("登录成功")

            time.sleep(1)

    #取steam页面
    @staticmethod 
    async def getSteamPage(title):
        try:  
            response = requests.get('http://127.0.0.1:9222/json/list')  
            for item in response.json():  
                if item['title'] == title:  
                    # 如果找到了，就打印并返回这个对象  
                    return item
        except Exception as e:  
            return None
        return None
    
    #结束所有steam进程
    @staticmethod 
    async def killSteam():
        process_name = "steam.exe"
        # 遍历所有活动进程  
        for proc in psutil.process_iter(['pid', 'name']):  
            try:  
                # 检查进程名称是否匹配  
                if proc.info['name'] == process_name:  
                    # 终止进程  
                    proc.terminate()  
                    print(f"进程 {process_name} (PID: {proc.info['pid']}) 已终止")  
                    break  
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):  
                pass  
        else:  
            print(f"未找到名为 {process_name} 的进程")
  
# 示例用法  
async def main():  
    # 设置要执行的命令行的路径  
    command_line = r"E:\steam\steam.exe"  
    
    # 初始化启动信息和进程信息对象  
    startup_info = win32process.STARTUPINFO()  
    
    # 调用CreateProcess函数来启动新的进程  
    try:  
        win32process.CreateProcess(  
            None,             # 应用程序名称  
            command_line,     # 要执行的命令行  
            None,             # 进程安全属性  
            None,             # 线程安全属性  
            0,                # 是否继承句柄  
            win32con.CREATE_NEW_CONSOLE, # 在新的控制台窗口中启动进程  
            None,             # 环境变量  
            None,             # 当前目录  
            win32process.STARTUPINFO() # 用于接收进程信息的对象  
        )  
        print("Steam has been started successfully.")  
    except Exception as e:  
        print(f"Failed to start Steam: {e}")  
    await RemoteDebugWebSocketClient.login("15870827663" , "wz8520qq" , "E:\\steam\\steam.exe")
    print("11")
  
if __name__ == '__main__':  
    asyncio.run(main())